using System.Collections.Generic;
using System.IO;
using Core;

namespace DoItNow.Features
{
	internal class OpenTestFeature : IncrementalSearchFeature
	{
		public OpenTestFeature(Ide ide, OutputPane outputPane)
			: base("Open Test", "Global::shift+alt+t", ide, outputPane)
		{
		}

		public override bool IsAvailable
		{
			get { return Ide.SolutionIsOpen; }
		}

		public override List<SearchEntry> CreateSearchEntries()
		{
			List<string> sourceFiles = Ide.FindFilesInSolution();
			sourceFiles.RemoveAll(match => IsTestFile(match) == false);

			return SearchEntry.CreateSearchEntries(sourceFiles);
		}

		public override void OnSearchSucceeded(object tag)
		{
			string testFilePath = (string) tag;
			string testFileName = Path.GetFileNameWithoutExtension(testFilePath);

			string implementationFileName = testFileName.Remove(0, 4);

			List<string> sourceFiles = Ide.FindFilesInSolution();
			List<string> candidates = sourceFiles.FindAll(match => Path.GetFileNameWithoutExtension(match) == implementationFileName);
			List<string> cppCandidates = candidates.FindAll(match => Path.GetExtension(match) == ".cpp");

			string implementationFilePath = (cppCandidates.Count > 0) ? cppCandidates[0] : candidates[0];

			Ide.CloseAllDocuments();
			Ide.OpenFile(testFilePath);
			Ide.OpenFile(implementationFilePath);
			Ide.SplitDocumentsVertically();
		}

		private static bool IsTestFile(string path)
		{
			return Path.GetFileName(path).StartsWith("Test") && Path.GetDirectoryName(path).Contains("Test");
		}
	}
}